<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');

/**
 * 分页配置 for CI
 * @param per 显示数目
 * @param row 总数
 * @param url 地址 
 **/
function page_config($per=0,$rows=0,$url){
	$config['base_url'] = $url;
	$config['total_rows'] = $rows;
	$config['per_page'] = $per; 
	$config['full_tag_open'] = '<div class="pagination"><ul>'; 
	$config['full_tag_close'] = '</ul></div>'; 
	$config['first_link'] = '首页';
	$config['first_tag_open'] = '<li>';
	$config['first_tag_colse'] = '</li>';
	$config['last_link'] = '末页';
	$config['last_tag_open'] = '<li>';
	$config['last_tag_colse'] = '</li>';
	$config['prev_link'] = '上一页';
	$config['prev_tag_open'] = '<li>';
	$config['prev_tag_colse'] = '</li>';
	$config['next_link'] = '下一页';
	$config['next_tag_open'] = '<li>';
	$config['next_tag_colse'] = '</li>';
	$config['num_tag_open'] = '<li>';
	$config['num_tag_colse'] = '</li>';
	$config['cur_tag_open'] = '<li class="active"><a href="#">';
	$config['cur_tag_colse'] = '</a></li>';
	return $config;
}

function show_msg($msg,$prefix = '', $suffix = ''){
	return  $prefix.$msg.$suffix."\n";
}

/**
 * 判断文件或文件夹是否存在，返回图标地址
 **/
function icon_file_exists($file){
	if(strpos($file,'/') !== 0){
		$file = MDPATH.'/'.$file;
	}
	if (file_exists($file)) {
		return "icon-ok";
	}else{
		return "icon-remove";
	}
}

/**
 * 建立目录 递归
 * @param dir string 要建立的文件夹的相对路径
 * @return mkdir 递归建立目录路径
 */
function mkdirs($dir){
	return is_dir($dir) or (mkdirs(dirname($dir)) and mkdir($dir, 0777));
}

/**
 * @param link string 文件地址
 * @param skin string 所属文件夹
 * @return 输出 script src 地址
 */
function link_script($link){
	$links= STATIC_URL.'js/'.$link."";
	return "<script src=\"$links\" type=\"text/javascript\" charset=\"utf-8\"></script>\n"; 
}

/**
 * @param link string 文件地址
 * @param skin string 所属文件夹
 * @return 输出 style link 地址
 */
function link_style($link){
	$links= STATIC_URL.'css/'.$link;
	return "<link href=\"$links\" rel=\"stylesheet\" type=\"text/css\" /></link>\n";
}

/**
 * @param link string 文件地址
 * @param skin string 所属文件夹
 * @return 输出 href image 地址
 */
function link_image($link){
	return STATIC_URL.'img/'.$link;
}

/**
 * 追加乱码 sha1 加密截取
 * @param string
 * @return 加密 
 **/
function shaMi($str){
	$str.='!@#$%^&*()';
	return substr(sha1($str),3,32);
}

/**
 * 转化提交表单
 * 输出utf-8编码
 * @param string
 **/
function html2($str){
	return htmlentities($str,ENT_QUOTES,"UTF-8"); 
}


/**
 * 判定手机浏览
 */
function isMobile(){

	$isMobile = false;
	$isBot = false;

	$op = isset($_SERVER['HTTP_X_OPERAMINI_PHONE'])?strtolower($_SERVER['HTTP_X_OPERAMINI_PHONE']):'';
	$ua = isset($_SERVER['HTTP_USER_AGENT'])?strtolower($_SERVER['HTTP_USER_AGENT']):'';
	$ac = strtolower($_SERVER['HTTP_ACCEPT']);
	$ip = $_SERVER['REMOTE_ADDR'];

	$isMobile = strpos($ac, 'application/vnd.wap.xhtml+xml') !== false
		|| $op != ''
		|| strpos($ua, 'sony') !== false 
		|| strpos($ua, 'symbian') !== false 
		|| strpos($ua, 'nokia') !== false 
		|| strpos($ua, 'samsung') !== false 
		|| strpos($ua, 'mobile') !== false
		|| strpos($ua, 'windows ce') !== false
		|| strpos($ua, 'epoc') !== false
		|| strpos($ua, 'opera mini') !== false
		|| strpos($ua, 'nitro') !== false
		|| strpos($ua, 'j2me') !== false
		|| strpos($ua, 'midp-') !== false
		|| strpos($ua, 'cldc-') !== false
		|| strpos($ua, 'netfront') !== false
		|| strpos($ua, 'mot') !== false
		|| strpos($ua, 'up.browser') !== false
		|| strpos($ua, 'up.link') !== false
		|| strpos($ua, 'audiovox') !== false
		|| strpos($ua, 'blackberry') !== false
		|| strpos($ua, 'ericsson,') !== false
		|| strpos($ua, 'panasonic') !== false
		|| strpos($ua, 'philips') !== false
		|| strpos($ua, 'sanyo') !== false
		|| strpos($ua, 'sharp') !== false
		|| strpos($ua, 'sie-') !== false
		|| strpos($ua, 'portalmmm') !== false
		|| strpos($ua, 'blazer') !== false
		|| strpos($ua, 'avantgo') !== false
		|| strpos($ua, 'danger') !== false
		|| strpos($ua, 'palm') !== false
		|| strpos($ua, 'series60') !== false
		|| strpos($ua, 'palmsource') !== false
		|| strpos($ua, 'pocketpc') !== false
		|| strpos($ua, 'smartphone') !== false
		|| strpos($ua, 'rover') !== false
		|| strpos($ua, 'ipaq') !== false
		|| strpos($ua, 'au-mic,') !== false
		|| strpos($ua, 'alcatel') !== false
		|| strpos($ua, 'ericy') !== false
		|| strpos($ua, 'up.link') !== false
		|| strpos($ua, 'vodafone/') !== false
		|| strpos($ua, 'wap1.') !== false
		|| strpos($ua, 'wap2.') !== false;

	$isBot =  $ip == '66.249.65.39' 
		|| strpos($ua, 'googlebot') !== false 
		|| strpos($ua, 'mediapartners') !== false 
		|| strpos($ua, 'yahooysmcm') !== false 
		|| strpos($ua, 'baiduspider') !== false
		|| strpos($ua, 'msnbot') !== false
		|| strpos($ua, 'slurp') !== false
		|| strpos($ua, 'ask') !== false
		|| strpos($ua, 'teoma') !== false
		|| strpos($ua, 'spider') !== false 
		|| strpos($ua, 'heritrix') !== false 
		|| strpos($ua, 'attentio') !== false 
		|| strpos($ua, 'twiceler') !== false 
		|| strpos($ua, 'irlbot') !== false 
		|| strpos($ua, 'fast crawler') !== false                        
		|| strpos($ua, 'fastmobilecrawl') !== false 
		|| strpos($ua, 'jumpbot') !== false
		|| strpos($ua, 'googlebot-mobile') !== false
		|| strpos($ua, 'yahooseeker') !== false
		|| strpos($ua, 'motionbot') !== false
		|| strpos($ua, 'mediobot') !== false
		|| strpos($ua, 'chtml generic') !== false
		|| strpos($ua, 'nokia6230i/. fast crawler') !== false;

	return $isMobile;
}


/**
 * 剪切字符串
 * @link thinkphp 来自thinkphp的字符串库文件
 * @access public
 * @param string $str
 * @param int $start 开始位置
 * @param int $length 截取长度
 * @param string charset 默认utf8
 * @param bool $suffix 显示后缀符号...
 * 
 * @return string
 */     
function msubstr($str, $start=0, $length, $charset="utf-8", $suffix=true)
{
	if(function_exists("mb_substr"))
		return mb_substr($str, $start, $length, $charset);
	elseif(function_exists('iconv_substr')) {
		return iconv_substr($str,$start,$length,$charset);
	}
	$re['utf-8']   = "/[\x01-\x7f]|[\xc2-\xdf][\x80-\xbf]|[\xe0-\xef][\x80-\xbf]{2}|[\xf0-\xff][\x80-\xbf]{3}/";
	$re['gb2312'] = "/[\x01-\x7f]|[\xb0-\xf7][\xa0-\xfe]/";
	$re['gbk']	  = "/[\x01-\x7f]|[\x81-\xfe][\x40-\xfe]/";
	$re['big5']	  = "/[\x01-\x7f]|[\x81-\xfe]([\x40-\x7e]|\xa1-\xfe])/";
	preg_match_all($re[$charset], $str, $match);
	$slice = join("",array_slice($match[0], $start, $length));
	if($suffix) return $slice."…";
	return $slice;
}

/** 
 * Strip a string from the end of a string 
 * 
 * @param string $str      the input string 
 * @param string $remove   OPTIONAL string to remove 
 *  
 * @return string the modified string 
 */ 
function rstrtrim($str, $remove=null) 
{ 
	$str    = (string)$str; 
	$remove = (string)$remove;    

	if(empty($remove)) 
	{ 
		return rtrim($str); 
	} 

	$len = strlen($remove); 
	$offset = strlen($str)-$len; 
	while($offset > 0 && $offset == strpos($str, $remove, $offset)) 
	{ 
		$str = substr($str, 0, $offset); 
		$offset = strlen($str)-$len; 
	} 

	return rtrim($str); 
} 

function utf8togbk($data){
	return iconv("UTF-8", "GB2312//IGNORE", $data); 
}

function gbktoutf8($data){
	return iconv("GB2312","UTF-8", $data); 
}

function logfile($str)
{
	$logfile=fopen('logfile.log',"a+");
	fwrite($logfile,"\r\n".$str);
	fclose($logfile);
}

function read_file($file)
{
	if ( ! file_exists($file))
	{
		return FALSE;
	}

	if (function_exists('file_get_contents'))
	{
		return file_get_contents($file);
	}

	if ( ! $fp = @fopen($file, FOPEN_READ))
	{
		return FALSE;
	}

	flock($fp, LOCK_SH);

	$data = '';
	if (filesize($file) > 0)
	{
		$data =& fread($fp, filesize($file));
	}

	flock($fp, LOCK_UN);
	fclose($fp);

	return $data;
}
function get_filenames($source_dir, $include_path = FALSE, $_recursion = FALSE)
{
	static $_filedata = array();

	if ($fp = @opendir($source_dir))
	{
		// reset the array and make sure $source_dir has a trailing slash on the initial call
		if ($_recursion === FALSE)
		{
			$_filedata = array();
			$source_dir = rtrim(realpath($source_dir), DIRECTORY_SEPARATOR).DIRECTORY_SEPARATOR;
		}

		while (FALSE !== ($file = readdir($fp)))
		{
			if (@is_dir($source_dir.$file) && strncmp($file, '.', 1) !== 0)
			{
				get_filenames($source_dir.$file.DIRECTORY_SEPARATOR, $include_path, TRUE);
			}
			elseif (strncmp($file, '.', 1) !== 0)
			{
				$_filedata[] = ($include_path == TRUE) ? $source_dir.$file : $file;
			}
		}
		return $_filedata;
	}
	else
	{
		return FALSE;
	}
}

function get_filename($source_dir, $url=FALSE)
{
    $_filedata = array("dirs"=>array(),"files"=>array());

    if ($fp = @opendir($source_dir))
    {
        if ($url === FALSE)
        {
            $_filedata = array("dirs"=>array(),"files"=>array());
            $source_dir = rtrim(realpath($source_dir), DIRECTORY_SEPARATOR).DIRECTORY_SEPARATOR;
        }

        $md_path = str_replace(MDPATH,'',$source_dir);

        while (FALSE !== ($file = readdir($fp)))
        {
            if (@is_dir($source_dir.$file) && strncmp($file, '.', 1) !== 0)
            {
                if ($url === FALSE) {
                    $_filedata['dirs'][$file] =  $source_dir.$file.DIRECTORY_SEPARATOR ;
                }else{
                    $d['id'] = md5($md_path.$file);
                    $d['title'] = $file;
                    $d['path'] = $md_path.$file.DIRECTORY_SEPARATOR ;
                    array_push($_filedata['dirs'],$d);
                }
            }
            elseif (strncmp($file, '.', 1) !== 0 )
            {
                $path_info = pathinfo($file);
                if(@$path_info['extension'] == 'md' && $path_info['filename'] != 'menu'){
                    if ($url === FALSE) {
                        $_filedata['files'][$file] = $source_dir.$file;
                    }else{
                        $ti = fopen($source_dir.$file,'r');
                        $title= htmlspecialchars(trim(str_replace("#",'',trim(fgets($ti)))),ENT_QUOTES);
                        fclose($ti);
                        //$f['id'] = md5($md_path.$file);
                        $f['title'] = $title;
                        $f['path'] = $md_path.$path_info['filename'];
                        array_push($_filedata['files'],$f);
                    }
                }
            }
        }
        return $_filedata;
    }
    else
    {
        return FALSE;
    }
}

